package com.wlz.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wlz
 * @date 2022-06-28  11:05 下午
 */
@Slf4j
@Component
public class AckListener implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 1. 获取 消息id
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 2. 获取 消息
            log.info("message: {}", new String(message.getBody()));

            // 3. 进行业务处理
            log.info("=====进行业务处理=======");

            // 模拟出现异常
//        int i = 5/0;

            // 4. 进行消息签收
            channel.basicAck(deliveryTag, true);
        } catch (IOException e) {
            // 拒绝签收
            // 第三个参数 : requeue：重回队列。如果设置为true，则消息重新回到queue，broker会重新发送该消息给消费端
            channel.basicNack(deliveryTag, true, true);
        }


    }
}
